/** 去除空格和换行 */
const formatText = str => {
  return str.replace(/[ \r\n]/g, '')
}

/** 获取时间戳 */
const timeStamp = () => {
  return Math.round(new Date().getTime() / 1000)
}

/** 获取随机字符串 */
const randomString = (num = 8) => {
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  const maxPos = chars.length
  let pwd = ''
  for (let i = 0; i < num; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd.trim()
}/** 获取用户通行证签名 */

const getSignature = (params, signType) => {
  // 获取参数中的key，并将键值组成的数组排序
  const paramKeys = Object.keys(params)
  const keysArray = paramKeys.sort((a, b) => a.localeCompare(b))

  // 秘钥拼接
  let signature = ''
  keysArray.map(
    item => (signature += `${item}=${encodeURIComponent(params[item])}&`)
  ) // 拼接请求参数
  signature = signature.substr(0, signature.length - 1) // 去除末尾&

  formatText(signature) // 去除字符串中的空格和换行

  // 服务不同签名方式不同
  const { user, bus, upload, other } = $config.server.signature
  let newSignature = ''
  if (signType === 'user') {
    newSignature = signature + user
  } else if (signType === 'upload') {
    newSignature = signature + upload
  } else if (signType === 'other') {
    newSignature = signature + other
  } else {
    newSignature = bus + signature + bus
  }

  // MD5对拼接字符串加密
  if (signType === 'bus') {
    params.signature = MD5(newSignature)
  } else {
    params.sign = MD5(newSignature)
  }

  return params
}

/**
 * @signType 1.通行证user 2.业务bus 3.文件上传upload 4.地址库other
 */

const formateData = (params, signType) => {
	let data = getSignature(params, signType)
	return data
}